<?php
/**
 * sqlite.inc
 * SQLite wrapper.
 * @copyright	Copyright(c) 2002-2010 Bjorn Winberg
 * @author		Bjorn Winberg <cms@anomalye.net>
 * @license		http://www.gnu.org/licenses/gpl.html GNU General Public License version 2 
 * @package		AnomalyWiki
 */
 
class SQLite extends Module{
	public static $MODULE_UID = 'sqlite';
	protected $mDb = false;
	protected $mDbCache = array();
	protected $mQueryCount = 0;
	
	/**
	 *
	 */
	public function __construct(){
		parent::__construct();
		$this->loadSettings();
		$this->setProperty('DATABASE_FULLDIR', ModuleFactory::getProperty('system', 'DATA_FULLDIR') . DIRECTORY_SEPARATOR . $this->localSetting('DB_NAME'));
	}
    
	public function generateView(){
		return '';
	}
	
	/**
	 *
	 */  
	public function dbQuery($aQuery){
		$this->mQueryCount++;
		return $this->mDb->query($aQuery);
	}
	
	/**
	 *
	 */  
	public function dbExecute($aQuery){
		$this->mQueryCount++;
		return $this->mDb->exec($aQuery);
	}
	
	/**
	 *
	 */
	public function dbOpen(){
		$this->mDb = new SQLite3($this->localProperty('DATABASE_FULLDIR'));
		$this->mDb->exec('PRAGMA synchronous=OFF');
		return true;
	}

	/**
	 *
	 */
	public function dbClose(){
		$this->mDb->close();
	}

	/**
	 *
	 */
	public function dbBeginTransaction(){
		$this->mDb->exec('BEGIN TRANSACTION');
		return true;
	}

	/**
	 *
	 */
	public function dbCommit(){
		$this->mDb->exec('COMMIT');
		return true;
	}
	
	public function dbLastId(){
		return $this->mDb->lastInsertRowid();
	}
	
	public function dbEscape($aString){
		return SQLite3::escapeString($aString);
	}
	
	public function dbValues($aValues, $aNoEscape = array()){
		$safeKeys = array();
		$safeValues = array();
		foreach($aValues as $key => $value){
			$safeKeys[] = $key;
			if(!isset($aNoEscape[$key])){
				$safeValues[] = "'" . SQLite3::escapeString($value) . "'";
			}
			else{
				$safeValues[] = $value;
			}
		}
		return '(' . implode(",", $safeKeys) . ') VALUES(' . implode(",", $safeValues) . ')';
	}
	
	/**
	 *
	 */
	public function dbGetQueryCount(){
		return $this->mQueryCount;
	}
}
?>
